//
//  simWeekViewController.m
//  simens
//
//  Created by 稳 张 on 12-7-29.
//  Copyright (c) 2012年 yst. All rights reserved.
//


#import "simTodayVisitorViewController.h"
#import "MAWeekView.h"
#import "NSDateCategories.h"
#import "ASIHTTPRequest.h"
#import "MAWeekView.h"
#import "simShopDetailController.h"
#import "JSONKit.h"

@interface simTodayVisitorViewController () <UITableViewDelegate, UITableViewDataSource, ASIHTTPRequestDelegate> {
	//TKCalendarMonthView *calendar;	
}

@property (nonatomic,strong) UITableView *shopTableView;
@property (strong) NSMutableArray* weekButtonArray;
@property (strong) ASIHTTPRequest *request;
@property (strong) NSMutableArray* visitorItemArray;
@property (strong) NSMutableArray* todayVisitorItemArray;
@property (strong) NSArray* markArray;

@end

@implementation simTodayVisitorViewController

@synthesize shopTableView = _shopTableView;
@synthesize weekButtonArray = _weekButtonArray;
@synthesize request = _request;
@synthesize visitorItemArray = _visitorItemArray;
@synthesize todayVisitorItemArray = _todayVisitorItemArray;
@synthesize markArray = _markArray;


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController.navigationBar setHidden:NO];
    
    [self.view setBackgroundColor:[UIColor clearColor]];
    
    self.title=@"今日计划拜访";
    
    //从服务器请求数据
    self.visitorItemArray = [[NSMutableArray alloc] init];
        
    self.shopTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 
                                                                       self.view.bounds.size.height-80) 
                                                      style:UITableViewStylePlain];  
    
    [self.shopTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.shopTableView setDelegate:self];
    [self.shopTableView setDataSource:self];
    self.shopTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview: self.shopTableView];
}


-(void) viewWillAppear:(BOOL)animated {
    
    if ([self isAccessibilityElement]==NO) {
        NSLog(@"dasdasdasdasd");
        
    }
}
-(void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    [self showMbprogress];
    
    NSDate* date = [NSDate date];
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateStr = [formatter stringFromDate:date];
    
    NSString *u=[NSString stringWithFormat:@"%@/getVisitSiemensCustomers?startDay=%@&endDay=%@&mobile=%@&pwd=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],dateStr,dateStr,[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"]];
    NSLog(@"request for url:%@",u);
    NSURL *url = [NSURL URLWithString:u];
    self.request = [ASIHTTPRequest requestWithURL:url];
    [self.request setDelegate:self];
    [self.request start];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}// Default is 1 if not implemented


//tableview行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    return [self.todayVisitorItemArray count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString* CellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    } 
    
    for (UIView *v in [cell subviews]) {
        if ([v isKindOfClass:[UILabel class]]|
            [v isKindOfClass:[UIImageView class]]) {
            [v removeFromSuperview];
        }
    }
    
    
    [cell.textLabel setBackgroundColor:[UIColor clearColor]];
    
    visitorItem* visitor = [self.todayVisitorItemArray objectAtIndex:indexPath.row];
    
    //        NSString* laberStr = [NSString stringWithFormat:@"%d: %@前来拜访！", indexPath.row+1, visitor.custName];
    //        [cell.textLabel setText:laberStr]; 
    //        cell.textLabel.font=[UIFont systemFontOfSize:18];
    //    
    
    if(visitor.visitNum.integerValue>visitor.visitedNum.integerValue){
        UIImage* img = [UIImage imageNamed:@"red.png"];    
        UIImageView *imageView =[[UIImageView alloc] initWithImage:img];
        [imageView setFrame:CGRectMake(3, 30, 20, 20)];
        [cell addSubview:imageView];
    }else{
        UIImage* img = [UIImage imageNamed:@"green.png"];    
        UIImageView *imageView =[[UIImageView alloc] initWithImage:img];
        [imageView setFrame:CGRectMake(0, 30, 25, 20)];
        [cell addSubview:imageView];
    }
    
    UILabel* shopnameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 180, 80)];
    [shopnameLabel setBackgroundColor:[UIColor clearColor]];
    [shopnameLabel setText:visitor.custNameEn]; 
    shopnameLabel.font=[UIFont systemFontOfSize:16];
    shopnameLabel.numberOfLines=3;
    [cell addSubview:shopnameLabel];
    
    UILabel* visitNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 5, 100, 20)];
    [visitNumLabel setBackgroundColor:[UIColor clearColor]];
    [visitNumLabel setText:[NSString stringWithFormat:@"计划拜访次数：%@",visitor.visitNum]];
    [visitNumLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitNumLabel.font=[UIFont systemFontOfSize:12];
    [cell addSubview:visitNumLabel];
    
    UILabel* visitedNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 25, 100, 20)];
    [visitedNumLabel setBackgroundColor:[UIColor clearColor]];
    [visitedNumLabel setText:[NSString stringWithFormat:@"已经拜访次数：%@",visitor.visitedNum]];
    [visitedNumLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitedNumLabel.font=[UIFont systemFontOfSize:12];
    [cell addSubview:visitedNumLabel];
    
    UILabel* visitdateLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 45, 100, 35)];
    [visitdateLabel setBackgroundColor:[UIColor clearColor]];
    [visitdateLabel setText:[NSString stringWithFormat:@"计划拜访时间：%@",visitor.visitDate]];
    [visitdateLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitdateLabel.font=[UIFont systemFontOfSize:12];
    visitdateLabel.numberOfLines=2;
    [cell addSubview:visitdateLabel];
    
    
    UIImage* seletedImg = [UIImage imageNamed:@"tableviewcellSelected.png"];    
    UIImageView *seletedImgView =[[UIImageView alloc] initWithImage:seletedImg];
    [cell setSelectedBackgroundView:seletedImgView];
    
    
    UIImage* backImg = [UIImage imageNamed:@"tableviewcell.png"];    
    UIImageView *backImgView =[[UIImageView alloc] initWithImage:backImg];
    [cell setBackgroundView:backImgView];
    

    
    return cell;
    
}

//row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 10;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return @"";
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self tableCellBeenPress:indexPath.row];
}

-(void) tableCellBeenPress:(int) index {
    simShopDetailController* shopController = [[simShopDetailController alloc] init];
    [shopController setCustomerItem:[self.todayVisitorItemArray objectAtIndex:index]];
    [self.navigationController pushViewController:shopController animated:YES]; 
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    
    [self.visitorItemArray removeAllObjects];
    if (!error) {
        NSString *response = [request responseString];
        NSLog(@"load data is :%@",response);
        NSDictionary* dict = [response objectFromJSONString];
        NSArray * dictArray=[dict objectForKey:@"siemensCustomer"];
        if(dictArray!=nil){
            NSMutableArray *marks = [NSMutableArray array];
            for(int i=0;i<dictArray.count;i++){
                NSDictionary* temp = [dictArray objectAtIndex:i];
                visitorItem *d=[[visitorItem alloc] init];
                NSString *date=[temp objectForKey:@"planVisitDate"];
                d.visitDate=[date substringToIndex:10];
                [marks addObject:[NSString stringWithFormat:@"%@ 00:00:00 +0000",d.visitDate]];
                NSLog(@"visit date is %@",d.visitDate);
                d.visitNum=[temp objectForKey:@"visitNum"];
                d.visitedNum=[temp objectForKey:@"visitedNum"];
                d.contactName=[temp objectForKey:@"corporateDeputy"];
                if([[temp objectForKey:@"custPhone"] isKindOfClass:[NSString class]]==NO){
                    d.contactPhone=[[temp objectForKey:@"custPhone"] stringValue];
                }else {
                    d.contactPhone=[temp objectForKey:@"custPhone"];
                }
                d.custId=[temp objectForKey:@"custDetailId"];
                d.datelineId=[temp objectForKey:@"datelineId"];
                d.custNameEn=[temp objectForKey:@"custNameEn"];
                [self.visitorItemArray addObject:d];
            }
            self.markArray=[NSArray arrayWithArray:marks];
        }
        
        self.todayVisitorItemArray = [[NSMutableArray alloc] initWithArray:self.visitorItemArray];
        
        
    }
    [self hideMbProgress];
    [self.shopTableView reloadData];
}


- (void)requestFailed:(ASIHTTPRequest *)request {
    [self hideMbProgress];
}


-(void) updateFromHttp {
    NSDate* date = [NSDate date];
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateStr = [formatter stringFromDate:date];

    NSString *u=[NSString stringWithFormat:@"%@/getVisitSiemensCustomers?startDay=%@&endDay=%@&mobile=%@&pwd=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],dateStr,dateStr,[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"]];
    NSLog(@"request for url:%@",u);
    NSURL *url = [NSURL URLWithString:u];
    if (self.request = nil) {
        self.request = [[ASIHTTPRequest alloc] initWithURL:url];
        [self.request setDelegate:self];
    }
    
    [self.request setURL:url];
    [self.request start];
}

@end
